package com.stellar.pay.core.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/4/4
 * @Description : 从pub_key.pem文件中读取 "微信支付公钥",也即是从 "pub_key.pem文件" 得到 "PublicKey" 类型的对象
 */
public class WxPayPublicKeyLoader {

    /**
     * @param pemFilePath pub_key.pem文件路径
     * @return PublicKey - 公钥对象
     */
    public static PublicKey loadPublicKey(String pemFilePath) {
        // 读取PEM文件内容
        String pemContent = null;
        try {
            pemContent = new String(Files.readAllBytes(Paths.get(pemFilePath)));
        } catch (IOException e) {
            throw new RuntimeException("pub_key.pem文件内容读取失败", e);
        }

        // 去除PEM文件头和尾部
        String base64EncodedKey = pemContent
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");

        try {
            // 将Base64编码的公钥转换为PublicKey对象
            byte[] decodedKey = Base64.getDecoder().decode(base64EncodedKey);

            // 构造X509EncodedKeySpec对象(编码密钥规范)，构造KeyFactory对像(密钥工厂)
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            // 生成公钥对象
            PublicKey publicKey = keyFactory.generatePublic(keySpec);

            return publicKey;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("pub_key.pem文件内容转换失败", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("SHA256withRSA 算法不存在");
        }
    }

}
